// 环境配置
const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env.development';
require('dotenv').config({ path: envFile });

// 导入依赖
const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const authRoutes = require('./routes/auth');
const practiceRouter = require('./routes/practice');

// 创建 Express 应用
const app = express();
const port = process.env.PORT || 3002;

// 配置日志
const logDir = path.join(__dirname, 'log');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

const accessLogStream = fs.createWriteStream(
  path.join(logDir, 'access.log'),
  { flags: 'a' }
);

// 配置 CORS
const corsOptions = {
  origin: process.env.NODE_ENV === 'development' 
    ? ['http://localhost:5173', 'http://127.0.0.1:5173']
    : ['http://fe.slinqueen.com', 'https://fe.slinqueen.com'],
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 86400
};

// 配置数据库连接池
const dbPool = mysql.createPool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 中间件
app.use(cors(corsOptions));
app.use(express.json());

// 访问日志中间件
app.use((req, res, next) => {
  const now = new Date();
  const log = `[${now.toISOString()}] ${req.method} ${req.url} - ${req.ip}\n`;
  accessLogStream.write(log);
  next();
});

// 路由配置
app.use('/api/auth', authRoutes);
app.use('/api/practice', practiceRouter);

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 反馈API
app.post('/api/feedback', async (req, res) => {
  try {
    const { content, email } = req.body;
    const ipAddress = req.ip;
    const userAgent = req.headers['user-agent'];

    if (!content) {
      return res.status(400).json({ error: '反馈内容不能为空' });
    }

    const connection = await dbPool.getConnection();
    try {
      const [result] = await connection.execute(
        'INSERT INTO math_practice_feedback (content, email, ip_address, user_agent) VALUES (?, ?, ?, ?)',
        [content, email || null, ipAddress, userAgent]
      );

      res.json({
        success: true,
        message: '反馈提交成功',
        feedbackId: result.insertId
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('保存反馈失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，请稍后重试'
    });
  }
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  });
});

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接
    const connection = await dbPool.getConnection();
    console.log('数据库连接成功');
    connection.release();

    // 打印启动信息
    console.log('=== 服务器启动信息 ===');
    console.log(`当前运行环境: ${process.env.NODE_ENV}`);
    console.log(`服务器端口: ${port}`);
    console.log(`数据库配置:`, {
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USER,
      database: process.env.DB_NAME
    });
    console.log(`CORS 配置:`, corsOptions);
    console.log('====================');

    // 启动服务器
    app.listen(port, () => {
      console.log(`服务器运行在 http://localhost:${port}`);
    });
  } catch (error) {
    console.error('服务器启动失败:', error);
    if (error.code === 'EADDRINUSE') {
      console.error(`端口 ${port} 已被占用，请尝试以下操作：`);
      console.error('1. 检查是否有其他服务正在运行');
      console.error('2. 使用 netstat -tulpn | grep :' + port + ' 查看端口占用');
      console.error('3. 使用 fuser -k ' + port + '/tcp 强制释放端口');
      console.error('4. 或者修改 .env 文件中的 PORT 配置');
    }
    process.exit(1);
  }
};

startServer(); 